import { _decorator } from "cc";

/**
 * 单例装饰器，用于简化类的单例模式实现
 * 使用方式：@Singleton
 */
export function Singleton<T extends { new (...args: any[]): {} }>(
  constructor: T
) {
  // 保存原始构造函数
  const originalConstructor = constructor;

  // 创建新的构造函数
  const newConstructor: any = function (...args: any[]) {
    if (!newConstructor._instance) {
      newConstructor._instance = new originalConstructor(...args);
    }
    return newConstructor._instance;
  };

  // 复制原型链
  newConstructor.prototype = originalConstructor.prototype;

  // 添加静态getInstance方法
  newConstructor.getInstance = function () {
    if (!newConstructor._instance) {
      newConstructor._instance = new originalConstructor();
    }
    return newConstructor._instance;
  };

  return newConstructor;
}
